from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *

import zmq
import pickle
import logging
logging.basicConfig(level=logging.NOTSET)

class ZeroMQSender(QThread):
	"""A listener receive sequence information from Cicero"""

	REQUEST_TIMEOUT = 5000
	REQUEST_RETRIES = 3

	def __init__(self, ip = "127.0.0.1", port=6666, message = {}):
		super(ZeroMQSender, self).__init__()
		self.context = zmq.Context()
		self.ip = ip
		self.port = port

		self.message = message
		self.state = 'clear'
		self.keep_running = False

	def connectAddress(self):
		self.socket = self.context.socket(zmq.REQ)
		self.socket.connect ("tcp://"+self.ip+":%d" % self.port)



	def closeSocket(self):
		if hasattr(self,'socket') == False:
			return
		self.socket.setsockopt(zmq.LINGER , 0)
		self.socket.close()

	def run(self):
		self.state = 'sending'
		self.connectAddress()

		self.socket.send(pickle.dumps(self.message))

		retries_left = self.REQUEST_RETRIES
	
		while self.keep_running:
			if (self.socket.poll(self.REQUEST_TIMEOUT) & zmq.POLLIN) != 0:
				reply = self.socket.recv_string()

				if reply == "Have Received Image":
					logging.info("Server replied OK ")
					break
				else:
					logging.error("Malformed reply from server: %s", reply)
					continue
			print(retries_left)
			retries_left -= 1
			logging.warning("No response from server")
			
			if retries_left == 0:
				logging.error("Server seems to be offline, abandoning")
				
				break
			# Socket is confused. Close and remove it.
			self.socket.setsockopt(zmq.LINGER, 0)
			self.socket.close()
			logging.info("Reconnecting to server…")
			# Create new connection
			self.connectAddress()
			logging.info("Resending ")
			self.socket.send(pickle.dumps(self.message))
		self.state = 'fininshed'
		self.closeSocket()

if __name__ == '__main__':
	app = QApplication([])
	pub = ZeroMQSender(ip ="127.0.0.1", port=6666 ,message={"me":"image:hello world"})
	pub.start()

	app.exec_()

